package com.tiancheng.trade.settlement.service.settlement.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.settlement.bo.MerchantBO;
import com.tiancheng.trade.settlement.enums.*;
import com.tiancheng.trade.settlement.exception.BusinessException;
import com.tiancheng.trade.settlement.feign.MerchantPaymentChannelService;
import com.tiancheng.trade.settlement.feign.OrderService;
import com.tiancheng.trade.settlement.mapper.settlement.*;
import com.tiancheng.trade.settlement.model.settlement.*;
import com.tiancheng.trade.settlement.service.settlement.IPaymentBillService;
import com.tiancheng.trade.settlement.service.settlement.ISettlementBillQueryService;
import com.tiancheng.trade.settlement.service.settlement.ISettlementRuleService;
import com.tiancheng.trade.settlement.vo.settlement.admin.res.*;
import com.tiancheng.trade.settlement.vo.settlement.api.GetSettlementRuleVO;
import com.tiancheng.trade.settlement.vo.settlement.merchantcontract.GetMerchantContractVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 清分查询
 */
@Slf4j
@Service
public class SettlementBillQueryService implements ISettlementBillQueryService {


    @Autowired
    private SettlementBillResultMapper settlementBillResultMapper;
    @Autowired
    private SettlementBillDataMapper settlementBillDataMapper;
    @Autowired
    private SettlementBankBillDetailMapper settlementBankBillDetailMapper;
    @Autowired
    private IPaymentBillService paymentBillService;
    @Autowired
    private ISettlementRuleService ruleService;
    @Autowired
    private MerchantPaymentChannelService merchantService;
    @Autowired
    private MerchantContractService merchantContractService;
    @Resource
    private OrderService orderService;
    @Autowired
    private SettlementWaitBillMapper waitBillMapper;
    @Autowired
    private FlowSubOrderMapper flowSubOrderMapper;

    @Override
    public SettlementBillDetailResVO queryDetailBySubOrderId(String subOrderId) throws BusinessException {
        SettlementBillDetailResVO billDetail = new SettlementBillDetailResVO();

        if (StringUtils.isBlank(subOrderId)) {
            return null;
        }
        //查子订单对账处理信息
        SettlementBillResult billResult = new SettlementBillResult();
        billResult.setSubOrderId(subOrderId);
        billResult = settlementBillResultMapper.querySubOrderSettlementInfoBySubOrderId(billResult);
        if (null != billResult) {
            //清分对账信息
            billDetail.setErrorAmount(billResult.getErrorAmount());
            billDetail.setBillCount(billResult.getBillCount());
            billDetail.setShouldBillDate(billResult.getShouldBillDate());
            billDetail.setCompleteDate(billResult.getCompleteDate());
            billDetail.setErrorRemark(billResult.getErrorRemark());
            billDetail.setErrorHandle(billResult.getErrorHandle());
            billDetail.setErrorHandleTime(billResult.getErrorHandleTime());
        }

        //子订单标记信息
        List<FlowSubOrder> flowSubOrder = new ArrayList<FlowSubOrder>();
        if (StringUtils.isNotEmpty(subOrderId)) {
            QueryWrapper<FlowSubOrder> conditions = new QueryWrapper<>();
            conditions.eq("sub_order_id", subOrderId);
            flowSubOrder = flowSubOrderMapper.selectList(conditions);
            billDetail.setFlowSubOrder(flowSubOrder);
        }

        //平台清分流水
        List<PlatformBillResVO> platList = new ArrayList<PlatformBillResVO>();
        if (StringUtils.isNotEmpty(subOrderId)) {
            platList = waitBillMapper.selectPlatformBill(subOrderId);
            if (CollectionUtils.isNotEmpty(platList)) {
                platList.forEach(a -> {
                    a.setCostTypeCn(CostTypeEnum.getDesc(a.getCostType()));
                    a.setBillStatusCn(MateStatusEnum.getDesc(a.getBillStatus()));
                });
            } else {
                // 清分待对账-平台清分流水信息
                platList = waitBillMapper.selectPlatformWaitBill(subOrderId);
                if (CollectionUtils.isNotEmpty(platList)) {
                    platList.forEach(a -> {
                        a.setCostTypeCn(CostTypeEnum.getDesc(a.getCostType()));
                        a.setBillStatusCn(BillStatusEnum.getDesc(a.getBillStatus()));
                    });
                }
            }
        }
        billDetail.setPlatformBillRes(platList);

        //银行清分流水
        List<SettlementBankBillDetail> bList = settlementBankBillDetailMapper.selectBankBill(subOrderId);
        if (CollectionUtils.isEmpty(bList)) {
            // 平台无银行有的数据查询
            bList = settlementBankBillDetailMapper.selectBankBillByBankOrderId(subOrderId);
        }
        if (CollectionUtils.isNotEmpty(bList)) {
            bList.forEach(a -> {
                a.setCostTypeCn(CostTypeEnum.getDesc(a.getCostType()));
                a.setPayTypeCn(PayWayEnum.getDesc(a.getPayType()));
                a.setBillStatusCn(MateStatusEnum.getDesc(a.getBillStatus()));
            });
        }
        billDetail.setBankBillRes(bList);

        //订单信息
        Result<SubOrderResVO> result = orderService.fetchQuerySubOrder(subOrderId);
        if (result.getRet() == 0) {
            SubOrderResVO subOrderResVO = result.getData();
            billDetail.setOrderRes(subOrderResVO);

            //支付订单号，渠道支付订单号,支付订单创建时间,支付订单交易时间,通道费率,支付渠道,订单金额,支付方式,按流水号
            if (null != subOrderResVO && null != subOrderResVO.getOrder()) {

                subOrderResVO.setOrderSource(OrderSourceEnum.getDesc(subOrderResVO.getOrder().getOrderSource()));
                subOrderResVO.setPayChannel(PaymentChannelEnum.getDesc(subOrderResVO.getOrder().getPayChannel()));
                subOrderResVO.setOrderAmount(subOrderResVO.getOrder().getOrderAmount());
                subOrderResVO.setPayWay(PayWayEnum.getDesc(subOrderResVO.getOrder().getPayWay()));

                String folwId = subOrderResVO.getOrder().getFlowId();
                PaymentBill paymentBill = paymentBillService.getPaymentBill(folwId);
                if (paymentBill != null) {
                    subOrderResVO.setPaymentId(paymentBill.getPaymentId());
                    subOrderResVO.setPayChannelOrderid(paymentBill.getPayChannelOrderid());
                    subOrderResVO.setOrderSource(OrderSourceEnum.getDesc(subOrderResVO.getOrder().getOrderSource()));
                    subOrderResVO.setPayCreateTime(paymentBill.getCreateTime());
                    subOrderResVO.setPayTime(paymentBill.getPayTime());
                    subOrderResVO.setRate(paymentBill.getRate());
                    subOrderResVO.setPayChannel(PaymentChannelEnum.getDesc(paymentBill.getPayChannel()));
                    subOrderResVO.setOrderAmount(paymentBill.getOrderAmount());
                    subOrderResVO.setPayWay(PayWayEnum.getDesc(paymentBill.getPayWay()));
                }
            }
        }

        //商户信息
        if (result.getRet() == 0) {
            SubOrderResVO subOrderResVO = result.getData();
            if (null != subOrderResVO) {
                Result<MerchantBO> merchantResult = merchantService.findMerchant(subOrderResVO.getMerchantCode());
                if (merchantResult.getRet() == 0) {
                    MerchantBO merchantBO = merchantResult.getData();
                    MerchantResVO merchant = new MerchantResVO();
                    if (merchantBO != null) {
                        BeanUtils.copyProperties(merchantBO, merchant);
                        merchant.setAccountTypeName(MerchantAccountTypeEnum.getDesc(merchant.getAccountType()));
                    }
                    GetMerchantContractVO contractVO = new GetMerchantContractVO();
                    contractVO.setMerchantCode(merchantBO.getMerchantCode());
                    List<MerchantContract> contractList = merchantContractService.findList(contractVO);
                    if (CollectionUtils.isNotEmpty(contractList)) {
                        merchant.setContractStartDate(contractList.get(0).getContractStartDate());
                        merchant.setContractEndDate(contractList.get(0).getContractEndDate());
                    }
                    billDetail.setMerchantRes(merchant);
                }
            }
        }

        //清分规则信息
        if (StringUtils.isNotEmpty(subOrderId)) {
            List<SettlementBillData> billDataList = settlementBillDataMapper.selectBillDataBySubOrderIds(Arrays.asList(subOrderId));
            if (CollectionUtils.isNotEmpty(billDataList)) {
                SettlementBillData billData = billDataList.get(0);
                GetSettlementRuleVO getSettlementRuleVO = new GetSettlementRuleVO();
                getSettlementRuleVO.setRuleCode(billData.getClearRuleCode());
                SettlementRule settlementRule = ruleService.getSettlementByParam(getSettlementRuleVO);
                SettlementRuleResVO rule = new SettlementRuleResVO();
                if (settlementRule != null) {
                    BeanUtils.copyProperties(settlementRule, rule);
                    //订单核销日期,应清算日期
                    if (CollectionUtils.isNotEmpty(platList)) {
                        rule.setVerifiedTime(billDataList.get(0).getVerifiedTime());
                        rule.setShouldClearDate(billDataList.get(0).getShouldClearDate());
                    }
                }
                billDetail.setSettlementRuleRes(rule);
            }
        }

        return billDetail;
    }

}
